using System;
using System.IO;
using System.Text;

namespace Silent.Application.Logger
{
    public class FileLogProvider : ILogProvider
    {
        private readonly long fileMaxSize;
        private readonly string filePartName;
        private readonly object locker = new object();
        private FileStream fileStream;
        private StreamWriter streamWriter;

        public string FileName
        {
            get { return string.Format("{0} {1:MM-dd-yy H-mm-ss}.txt", filePartName, DateTime.Now); }
        }

        public FileLogProvider(string filePartName, long fileMaxSize)
        {
            this.filePartName = filePartName;
            this.fileMaxSize = fileMaxSize;
            fileStream = File.Open(FileName, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite);
            streamWriter = new StreamWriter(fileStream, Encoding.UTF8);
        }

        public void Log(LogType type, object log)
        {
            if (log == null)
                return;

            lock (locker)
            {
                CheckFile();
                streamWriter.WriteLine("[{0}] {1}: {2}", DateTime.Now, type, log);
                streamWriter.Flush();
            }
        }
        private void CheckFile()
        {
            var info = new FileInfo(fileStream.Name);
            if (info.Length >= fileMaxSize)
            {
                fileStream = File.Open(FileName, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite);
                streamWriter = new StreamWriter(fileStream, Encoding.UTF8);
            }
        }
    }
}